import {
	defineStore
} from 'pinia';
import api from '@/api/history.js';
import pic from '@/api/pics.js';

export const useHistoryStore = defineStore('history', {
	state: () => ({
		list: [],
		getClickable: true,
		page: 1,
		limit: 12,
		status: 'more',
		sortOrder: 'asc',
		up: 'up',
		contentText: {
			contentdown: "点击显示更多",
			contentrefresh: "正在加载...",
			contentnomore: "没有更多数据了"
		}
	}),
	actions: {
		async getData() {
			this.page = 1;
			const data = {
				userName: uni.getStorageSync('userName'),
				page: this.page,
				limit: this.limit,
			};
			this.status = 'more';
			const res = await api.getHistory(data);
			if (res.data.length !== 0) {
				this.list = res.data;
				uni.stopPullDownRefresh();
				this.list.sort((a, b) => {
					const dateA = new Date(a.date);
					const dateB = new Date(b.date);
					return this.sortOrder === 'asc' ? dateA - dateB : dateB - dateA;
				});
			}
		},
		async addList() {
			this.page++;
			this.status = 'loading';
			const data = {
				userName: uni.getStorageSync('userName'),
				page: this.page,
				limit: this.limit,
			};
			const res = await api.getHistory(data);
			if (res.data.length !== 0) {
				const newData = res.data;
				this.status = 'more';
				newData.sort((a, b) => {
					const dateA = new Date(a.date);
					const dateB = new Date(b.date);
					return this.sortOrder === 'asc' ? dateA - dateB : dateB - dateA;
				});
				this.list = this.list.concat(newData);
			} else {
				
				this.status = 'noMore';
			}
		},
		toggleSortOrder() {
			this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
			this.up = this.up === 'up' ? 'down' : 'up';
			if (this.list) {
				this.list.sort((a, b) => {
					const dateA = new Date(a.date);
					const dateB = new Date(b.date);
					return this.sortOrder === 'asc' ? dateA - dateB : dateB - dateA;
				});
			}
		},
		async delImg(imgName) {
			try {
				const res = await uni.showModal({
					title: '提示',
					content: '是否确认删除',
				});
				if (res.confirm) {
					const picRes = await pic.deleteImg({
						fileName: imgName
					});
					if (picRes.code === 200) {
						uni.showToast({
							title: "删除成功",
							icon: "success"
						});
					} else {
						uni.showToast({
							title: "删除失败",
							icon: "error"
						});
					}
				} else if (res.cancel) {
					uni.showToast({
						title: "删除取消",
						icon: "error"
					});
				}
				this.getData();
			} catch (e) {
				uni.showToast({
					title: "异常",
					icon: "error"
				});
				console.log(e);
			}
		},
	},
});